//
//  ServieJobStatusPopView.swift
//  GreenDeal
//
//  Created by Moennig Q on 14/12/2022.
//

import UIKit
import SnapKit
import RxGesture
import RxSwift
import RxCocoa
class ServieJobStatusPopView: View {
    fileprivate lazy var disposeBag = DisposeBag()
    //MARK: - 应用按钮
    let applyLabel = ContentLabel(R.font.interMedium(size: 17), hexStr: "#379657FF")
    //MARK: - 当前选择的值
    private var jobStatus: String = ServiceJobStatusName.all.rawValue
    private var paymentStatus: String = ServicePaymentStatusName.all.rawValue
    //MARK: - 按钮左右两边的margin和
    let leftRightMargin: CGFloat = 20
    //MARK: - 按钮之间的间距
    let btnsInternal: CGFloat = 10
    //MARK: - 按钮的高度
    let btnHeight: CGFloat = 34
    
    //MARK: - job status
    let startedStatusLabel = JobStatusLabel(ServiceJobStatusName.started.rawValue)
    let unqualifiedStatusLabel = JobStatusLabel(ServiceJobStatusName.unqualified.rawValue)
    let scheduledStatusLabel = JobStatusLabel(ServiceJobStatusName.scheduled.rawValue)
    let finishedStatusLabel = JobStatusLabel(ServiceJobStatusName.finished.rawValue)
    let appprovedStatusLabel = JobStatusLabel(ServiceJobStatusName.approved.rawValue)
    //MARK: - payment status
    let openStatusLabel = JobStatusLabel(ServicePaymentStatusName.open.rawValue)
    let paidStatusLabel = JobStatusLabel(ServicePaymentStatusName.paid.rawValue)
    var applyClosure: ((String,String)->Void)?
    //MARK: -
    override func setUpView() {
        self.backgroundColor = UIColor(hexStr: "#00000080")
        
        let btnsPerRow: CGFloat = (UIDevice.getCurrentDeviceType() == APPConfig.iPadType ? 5 : 2)
        let btnsWidth: CGFloat = (APPConfig.WidthForPortrait - self.leftRightMargin * 2 - self.btnsInternal * (btnsPerRow - 1)) / btnsPerRow
        
        let backView = UIView()
        backView.backgroundColor = .white
        backView.drawCorner(byRoundingCorners: [.topLeft,.topRight],radii: 10)
        self.addSubview(backView)
        backView.snp.makeConstraints { make in
            make.bottom.equalToSuperview()
            make.height.greaterThanOrEqualTo(0)
            make.left.right.equalToSuperview()
            make.centerX.equalToSuperview()
        }
        //clear btn
        let clearAllLabel = ContentLabel(R.font.interMedium(size: 17), hexStr: "#292D32B2")
        clearAllLabel.text = R.string.localizable.clearAll()
        backView.addSubview(clearAllLabel)
        clearAllLabel.snp.makeConstraints { make in
            make.top.equalTo(10)
            make.left.equalTo(leftRightMargin)
            make.height.equalTo(40)
            make.width.greaterThanOrEqualTo(0)
        }
        //apply btn
        applyLabel.text = R.string.localizable.apply()
        backView.addSubview(applyLabel)
        applyLabel.snp.makeConstraints { make in
            make.centerY.height.equalTo(clearAllLabel)
            make.right.equalTo(-leftRightMargin)
            make.width.greaterThanOrEqualTo(0)
        }
        //line view
        let lineView = View(hexStr: Constant.SeparatorColorHexStr)
        backView.addSubview(lineView)
        lineView.snp.makeConstraints { make in
            make.top.equalTo(60)
            make.left.right.equalToSuperview()
            make.height.equalTo(1)
        }
        //job status title
        let jobStatusTitle = ContentLabel(R.font.interSemiBold(size: 17),hexStr: "#292D32FF")
        jobStatusTitle.text = R.string.localizable.jobStatus()
        backView.addSubview(jobStatusTitle)
        jobStatusTitle.snp.makeConstraints { make in
            make.top.equalTo(lineView.snp.bottom).offset(20)
            make.left.equalTo(leftRightMargin)
            make.size.greaterThanOrEqualTo(0)
        }
        //******jobStatusBtnsBackView
        let jobStatusBtnsBackView = UIView()
        jobStatusBtnsBackView.backgroundColor = .white
        backView.addSubview(jobStatusBtnsBackView)
        jobStatusBtnsBackView.snp.makeConstraints { make in
            make.top.equalTo(jobStatusTitle.snp.bottom).offset(16)
            make.left.equalTo(leftRightMargin)
            make.right.equalTo(-leftRightMargin)
            make.height.greaterThanOrEqualTo(0)
        }
        //第一行,前两个都是有的
        jobStatusBtnsBackView.addSubview(startedStatusLabel)
        startedStatusLabel.snp.makeConstraints { make in
            make.left.top.equalToSuperview()
            make.height.equalTo(btnHeight)
            make.width.equalTo(btnsWidth)
        }
        jobStatusBtnsBackView.addSubview(unqualifiedStatusLabel)
        unqualifiedStatusLabel.snp.makeConstraints { make in
            make.top.equalToSuperview()
            make.left.equalTo(startedStatusLabel.snp.right).offset(10)
            make.height.equalTo(btnHeight)
            make.width.equalTo(btnsWidth)
        }
        if btnsPerRow == 2{//iPhone,job status 每行显示两个
            //第二行
            jobStatusBtnsBackView.addSubview(scheduledStatusLabel)
            scheduledStatusLabel.snp.makeConstraints { make in
                make.left.equalToSuperview()
                make.top.equalTo(startedStatusLabel.snp.bottom).offset(16)
                make.height.equalTo(btnHeight)
                make.width.equalTo(btnsWidth)
            }
            jobStatusBtnsBackView.addSubview(finishedStatusLabel)
            finishedStatusLabel.snp.makeConstraints { make in
                make.top.equalTo(scheduledStatusLabel)
                make.left.equalTo(scheduledStatusLabel.snp.right).offset(10)
                make.height.equalTo(btnHeight)
                make.width.equalTo(btnsWidth)
            }
            //第三行
            jobStatusBtnsBackView.addSubview(appprovedStatusLabel)
            appprovedStatusLabel.snp.makeConstraints { make in
                make.left.equalToSuperview()
                make.top.equalTo(scheduledStatusLabel.snp.bottom).offset(16)
                make.height.equalTo(btnHeight)
                make.width.equalTo(btnsWidth)
                make.bottom.equalToSuperview()
            }
        }else{//其他显示5个，iPad
            jobStatusBtnsBackView.addSubview(scheduledStatusLabel)
            scheduledStatusLabel.snp.makeConstraints { make in
                make.top.equalToSuperview()
                make.left.equalTo(unqualifiedStatusLabel.snp.right).offset(10)
                make.height.equalTo(btnHeight)
                make.width.equalTo(btnsWidth)
            }
            jobStatusBtnsBackView.addSubview(finishedStatusLabel)
            finishedStatusLabel.snp.makeConstraints { make in
                make.top.equalToSuperview()
                make.left.equalTo(scheduledStatusLabel.snp.right).offset(10)
                make.height.equalTo(btnHeight)
                make.width.equalTo(btnsWidth)
            }
            jobStatusBtnsBackView.addSubview(appprovedStatusLabel)
            appprovedStatusLabel.snp.makeConstraints { make in
                make.top.equalToSuperview()
                make.left.equalTo(finishedStatusLabel.snp.right).offset(10)
                make.height.equalTo(btnHeight)
                make.width.equalTo(btnsWidth)
                make.bottom.equalToSuperview()
            }
        }
        //**********payment status title
        let paymentStatusTitle = ContentLabel(R.font.interSemiBold(size: 17),hexStr: "#292D32FF")
        paymentStatusTitle.text = R.string.localizable.paymentStatus()
        backView.addSubview(paymentStatusTitle)
        paymentStatusTitle.snp.makeConstraints { make in
            make.top.equalTo(jobStatusBtnsBackView.snp.bottom).offset(30)
            make.left.equalTo(jobStatusTitle)
            make.size.greaterThanOrEqualTo(0)
        }
        //open
        backView.addSubview(openStatusLabel)
        openStatusLabel.snp.makeConstraints { make in
            make.top.equalTo(paymentStatusTitle.snp.bottom).offset(16)
            make.left.equalTo(jobStatusTitle)
            make.height.equalTo(btnHeight)
            make.width.equalTo(btnsWidth)
            make.bottom.equalToSuperview().offset(-65)
        }
        //open
        backView.addSubview(paidStatusLabel)
        paidStatusLabel.snp.makeConstraints { make in
            make.centerY.equalTo(openStatusLabel)
            make.left.equalTo(openStatusLabel.snp.right).offset(10)
            make.height.equalTo(btnHeight)
            make.width.equalTo(btnsWidth)
        }
        
        //上方空白区域，点击时关闭view
        let blankView = UIView()
        blankView.backgroundColor = .clear
        self.addSubview(blankView)
        blankView.snp.makeConstraints { make in
            make.top.left.right.equalToSuperview()
            make.height.greaterThanOrEqualTo(0)
            make.bottom.equalTo(backView.snp.top)
        }
        //点击空白区域关闭此pop view
        blankView.rx.tapGesture().when(.recognized).subscribe(onNext: { [weak self] _ in
            self?.removeFromSuperview()
        }).disposed(by: self.disposeBag)
        //MARK: - 两个按钮的点击
        //clear all绑定
        clearAllLabel.rx.tapGesture().when(.recognized).subscribe(onNext: { [weak self] _ in
            self?.clearAll()
        }).disposed(by: self.disposeBag)
        //apply绑定
        applyLabel.rx.tapGesture().when(.recognized).subscribe(onNext: { [weak self] _ in
            guard let strongSelf = self else { return  }
            strongSelf.applyClosure?(strongSelf.jobStatus, strongSelf.paymentStatus)
            strongSelf.removeFromSuperview()
        }).disposed(by: self.disposeBag)
        //MARK: - job status五个按钮的点击
        //started label绑定
        startedStatusLabel.rx.tapGesture().when(.recognized).subscribe(onNext: { [weak self] _ in
            guard let strongSelf = self else { return  }
            strongSelf.selJobStatus(ServiceJobStatusName.started.rawValue)
        }).disposed(by: self.disposeBag)
        //unqualified label绑定
        unqualifiedStatusLabel.rx.tapGesture().when(.recognized).subscribe(onNext: { [weak self] _ in
            guard let strongSelf = self else { return  }
            strongSelf.selJobStatus(ServiceJobStatusName.unqualified.rawValue)
        }).disposed(by: self.disposeBag)
        //scheduled label绑定
        scheduledStatusLabel.rx.tapGesture().when(.recognized).subscribe(onNext: { [weak self] _ in
            guard let strongSelf = self else { return  }
            strongSelf.selJobStatus(ServiceJobStatusName.scheduled.rawValue)
        }).disposed(by: self.disposeBag)
        //finished label绑定
        finishedStatusLabel.rx.tapGesture().when(.recognized).subscribe(onNext: { [weak self] _ in
            guard let strongSelf = self else { return  }
            strongSelf.selJobStatus(ServiceJobStatusName.finished.rawValue)
        }).disposed(by: self.disposeBag)
        //approved label绑定
        appprovedStatusLabel.rx.tapGesture().when(.recognized).subscribe(onNext: { [weak self] _ in
            guard let strongSelf = self else { return  }
            strongSelf.selJobStatus(ServiceJobStatusName.approved.rawValue)
        }).disposed(by: self.disposeBag)
        //MARK: - payment status五个按钮的点击
        //open label绑定
        openStatusLabel.rx.tapGesture().when(.recognized).subscribe(onNext: { [weak self] _ in
            guard let strongSelf = self else { return  }
            strongSelf.selPaymentStatus(ServicePaymentStatusName.open.rawValue)
        }).disposed(by: self.disposeBag)
        //paid label绑定
        paidStatusLabel.rx.tapGesture().when(.recognized).subscribe(onNext: { [weak self] _ in
            guard let strongSelf = self else { return  }
            strongSelf.selPaymentStatus(ServicePaymentStatusName.paid.rawValue)
        }).disposed(by: self.disposeBag)
    }
    func initData(jobStatus: String, paymentStatus: String){
        self.jobStatus = jobStatus
        self.paymentStatus = paymentStatus
        self.initJobStatus(jobStatus)
        self.initPaymentStatus(paymentStatus)
        
    }
    //MARK: -初始化job status
    private func initJobStatus(_ jobStatus: String){
        self.unSelAllJobStatus()
        if jobStatus.contains(ServiceJobStatusName.started.rawValue + ","){
            startedStatusLabel.setSelect(onFlag: true)
        }
        if jobStatus.contains(ServiceJobStatusName.scheduled.rawValue + ","){
            scheduledStatusLabel.setSelect(onFlag: true)
        }
        if jobStatus.contains(ServiceJobStatusName.finished.rawValue + ","){
            finishedStatusLabel.setSelect(onFlag: true)
        }
        if jobStatus.contains(ServiceJobStatusName.approved.rawValue + ","){
            appprovedStatusLabel.setSelect(onFlag: true)
        }
        if jobStatus.contains(ServiceJobStatusName.unqualified.rawValue + ","){
            unqualifiedStatusLabel.setSelect(onFlag: true)
        }
    }
    //MARK: -初始化payment status
    private func initPaymentStatus(_ paymentStatus: String){
        self.unSelAllPaymentStatus()
        if paymentStatus.contains(ServicePaymentStatusName.open.rawValue + ","){
            openStatusLabel.setSelect(onFlag: true)
        }
        if paymentStatus.contains(ServicePaymentStatusName.paid.rawValue + ","){
            paidStatusLabel.setSelect(onFlag: true)
        }
    }
    //MARK: - 抽取选择或不选的方法
    private func selectJobStatusByValue(status: String, onFlag: Bool){
        switch status {
        case ServiceJobStatusName.started.rawValue:
            startedStatusLabel.setSelect(onFlag: onFlag)
        case ServiceJobStatusName.unqualified.rawValue:
            unqualifiedStatusLabel.setSelect(onFlag: onFlag)
        case ServiceJobStatusName.scheduled.rawValue:
            scheduledStatusLabel.setSelect(onFlag: onFlag)
        case ServiceJobStatusName.approved.rawValue:
            appprovedStatusLabel.setSelect(onFlag: onFlag)
        case ServiceJobStatusName.finished.rawValue:
            finishedStatusLabel.setSelect(onFlag: onFlag)
        default:
            break
        }
    }
    private func selectPaymentStatisByValue(status: String, onFlag: Bool){
        switch status {
        case ServicePaymentStatusName.open.rawValue:
            openStatusLabel.setSelect(onFlag: onFlag)
        case ServicePaymentStatusName.paid.rawValue:
            paidStatusLabel.setSelect(onFlag: onFlag)
        default:
            break
        }
    }
    private func selJobStatus(_ status: String){
        if self.jobStatus == ServiceJobStatusName.all.rawValue {
            self.jobStatus = status + ","
            self.selectJobStatusByValue(status: status, onFlag: true)
        }else{
            if self.jobStatus.contains(status + ","){//取消选择
                self.jobStatus = self.jobStatus.replacingOccurrences(of: status + ",", with: "")
                if self.jobStatus == "" {
                    self.jobStatus = ServiceJobStatusName.all.rawValue
                }
                self.selectJobStatusByValue(status: status, onFlag: false)
            }else{
                self.jobStatus += status + ","
                self.selectJobStatusByValue(status: status, onFlag: true)
            }
        }
    }
    private func selPaymentStatus(_ status: String){
        if self.paymentStatus == ServicePaymentStatusName.all.rawValue {
            self.paymentStatus = status + ","
            self.selectPaymentStatisByValue(status: status, onFlag: true)
        }else{
            if self.paymentStatus.contains(status + ","){//取消选择
                self.paymentStatus = self.paymentStatus.replacingOccurrences(of: status + ",", with: "")
                if self.paymentStatus == "" {
                    self.paymentStatus = ServicePaymentStatusName.all.rawValue
                }
                self.selectPaymentStatisByValue(status: status, onFlag: false)
            }else{
                self.paymentStatus += status + ","
                self.selectPaymentStatisByValue(status: status, onFlag: true)
            }
        }
    }
    private func clearAll(){
        //清空选择的值
        jobStatus = ServiceJobStatusName.all.rawValue
        paymentStatus = ServicePaymentStatusName.all.rawValue
        //
        unSelAllJobStatus()
        unSelAllPaymentStatus()
    }
    //MARK: - 取消全部选择
    private func unSelAllJobStatus(){
        startedStatusLabel.setSelect(onFlag: false)
        scheduledStatusLabel.setSelect(onFlag: false)
        finishedStatusLabel.setSelect(onFlag: false)
        appprovedStatusLabel.setSelect(onFlag: false)
        unqualifiedStatusLabel.setSelect(onFlag: false)
    }
    
    //MARK: - 取消payment status全部选择
    private func unSelAllPaymentStatus(){
        openStatusLabel.setSelect(onFlag: false)
        paidStatusLabel.setSelect(onFlag: false)
    }
}
class JobStatusLabel: PaddingLabel{
    init(_ text: String) {
        super.init(frame: CGRect.zero)
        self.initView(text)
    }
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    private func initView(_ text: String) {
        self.text = text
        self.textAlignment = .center
        self.setFont(R.font.interMedium(size: 15))
        self.textColor = UIColor(hexStr: "#292D32B2")
        self.backgroundColor = UIColor(hexStr: "#F5F5F5")
        self.layer.cornerRadius = 3
        self.clipsToBounds = true
    }
    func setSelect(onFlag: Bool){
        self.textColor = onFlag ? UIColor(hexStr: "#379657") : UIColor(hexStr: "#292D32B2")
        self.backgroundColor = onFlag ? UIColor(hexStr: "#3796571A") : UIColor(hexStr: "#F5F5F5")
    }
}
